<?php

/**
 * @file
 * Contains \Drupal\libsys\Plugin\QueueWorker\EnableTeacher.
 */

namespace Drupal\libsys\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 * Enable certian teacher.
 *
 * @QueueWorker(
 *   id = "libsys_enable_teacher",
 *   title = @Translation("Enable certain teacher"),
 *   cron = {"time" = 60}
 * )
 */
class EnableTeacher extends QueueWorkerBase {

  /**
   * {@inheritdoc}
   */
  public function processItem($reader_info) {
	$reader=$reader_info[0];
	$status=$reader_info[1];
	// First let's fetch all the database settings
	$libsys_database = \Drupal::config('libsys.datasource');
	
	try {
		// Use php-oci8 rather than pdo_oci to deal with blob data, which is faster
		$conn=oci_connect($libsys_database->get('username'), $libsys_database->get('password'),
			sprintf("%s:%s/%s", $libsys_database->get('host'), $libsys_database->get('port'), $libsys_database->get('database')), 'AL32UTF8'
		);
		if(!$conn) {
			$e=oci_error();
			throw new \Exception($e['message']);
		}
		
		if(!empty($reader)) {
			// Get CERT_ID from barcode
			$enddate=new \DateTime();
			$enddate->setDate((int)date('Y')+1,6,30);
			$sql=sprintf("UPDATE READER_CERT SET CERT_FLAG='%s', END_DATE='%s' WHERE REDR_CERT_ID='%s' AND END_DATE<'%s'",
				$status, $enddate->format('Y-m-d'), $reader, $enddate->format('Y-m-d'));
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}

			$sql=sprintf("SELECT CERT_ID FROM READER_CERT WHERE REDR_CERT_ID='%s'", $reader);
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$row=oci_fetch_row($stmt);
			if(!empty($row)) {
				$cert_id=$row[0];
				$sql=sprintf("UPDATE READER SET REDR_DEL_DAY=NULL, REDR_FLAG='1' WHERE CERT_ID='%s' AND REDR_FLAG='0'", $cert_id);
				$stmt = oci_parse($conn, $sql);
				$r=oci_execute($stmt, OCI_DEFAULT);
			}
		}
	} catch (\Exception $e) {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
		throw new \Exception($e->getMessage());
	} finally {
		oci_commit($conn);
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
	}
  }
}
?>
